package com.whut.whw.goodsdetail;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.whut.whw.R;
import com.whut.whw.base.BaseActivity;
import com.whut.whw.find.MySwipeRefreshLayout;
import com.whut.whw.util.GsonUtils;
import com.whut.whw.util.LogUtils;
import com.whut.whw.util.ScreenUtils;
import com.whut.whw.util.ToastUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;

import static com.whut.whw.constant.ConfigConsts.GOODS_DETAIL_FLAG;

/**
 * <pre>
 *     author : 杨丽金
 *     time   : 2017/06/12
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class GoodsDetailAndDisposeActivity extends BaseActivity {
    @BindView(R.id.srl_find_refresh)
    MySwipeRefreshLayout mySwipeRefreshLayout;
    @BindView(R.id.rv_goodsDetail_list)
    RecyclerView mRecycleView;
    @BindView(R.id.tv_goodsItem_like)
    TextView mTvLike;// 点赞tv
    @BindView(R.id.tv_goodsItem_star)
    TextView mTvStar;// 收藏tv
    @BindView(R.id.tv_goodsItem_want)
    TextView mTvWant;// 想要tv
    @BindView(R.id.tv_goodsItem_comment)
    TextView mTvComment;// 评论tv
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.tv_agree)
    TextView mTvAgree;// 同意tv
    @BindView(R.id.tv_refuse)
    TextView mTvRefuse;// 拒绝tv

    @BindView(R.id.ll_exchangereq_bottom)
    View mLlExchangereqBottom;
    @BindView(R.id.ll_goods_detail_bottom)
    View mLlGoodsDetailBottom;

    private String[] mUrls = new String[]{"http://ww2.sinaimg.cn/large/c85e4a5cgw1f62hzfvzwwj20hs0qogpo.jpg",
            "http://ww2.sinaimg.cn/large/c85e4a5cgw1f62hzfvzwwj20hs0qogpo.jpg",
            "http://ww2.sinaimg.cn/large/c85e4a5cgw1f62hzfvzwwj20hs0qogpo.jpg",
            "http://ww2.sinaimg.cn/large/c85e4a5cgw1f62hzfvzwwj20hs0qogpo.jpg",
            "http://ww2.sinaimg.cn/large/c85e4a5cgw1f62hzfvzwwj20hs0qogpo.jpg",
//        "http://img5.imgtn.bdimg.com/it/u=1444023808,3753293381&fm=21&gp=0.jpg",
//        "http://img4.imgtn.bdimg.com/it/u=882039601,2636712663&fm=21&gp=0.jpg",
//        "http://img4.imgtn.bdimg.com/it/u=4119861953,350096499&fm=21&gp=0.jpg",
//        "http://img5.imgtn.bdimg.com/it/u=2437456944,1135705439&fm=21&gp=0.jpg",
//        "http://img2.imgtn.bdimg.com/it/u=3251359643,4211266111&fm=21&gp=0.jpg",
//        "http://img4.duitang.com/uploads/item/201506/11/20150611000809_yFe5Z.jpeg",
//        "http://img5.imgtn.bdimg.com/it/u=1717647885,4193212272&fm=21&gp=0.jpg",
            "http://ww2.sinaimg.cn/large/c85e4a5cgw1f62hzfvzwwj20hs0qogpo.jpg"};
    private static final String TAG = "GoodsDetailAndDisposeActivity";
    // “我想换”dialog中物品列表适配器
    GoodsListAdapter myGoodsListAdapter;
    // 想换对话框选中的物品position
    private int currentNum = -1;
    // “我想换”dialog
    AlertDialog dialog;
    // Activity中评论列表适配器
    CommentRecycleAdapter myCommentAdapter;
    // 标志是否正在上拉加载数据
    private boolean isLoading = false;
    // 标志该帖子是否已点赞
    private boolean hasLiked = false;
    // 标志该帖子是否已收藏
    private boolean hasStared = false;
    // 标志是否同意该换物请求
    private boolean hasAgreed = false;
    // 标志是否拒绝该换物请求
    private boolean hasRefused = false;

    private int page_flag = 0;


    @Override
    public int getLayoutId() {
        return R.layout.activity_goodsdetail;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        // 判断显示哪个页面
        Intent intent = getIntent();
        Bundle data = intent.getExtras();
        String id = data.getString("id");
        page_flag = data.getInt("pageFlag");
        if (page_flag == GOODS_DETAIL_FLAG) {
            showGoodsDetailPage();
        } else {
            showDisposeExchangeReqPage();
        }
        getinitData();
        initToolbar();
        initSwipeRefresh();
        initRecycleView();
        initBottomBar();
    }

    // 显示处理换物请求页
    private void showDisposeExchangeReqPage() {
        mLlGoodsDetailBottom.setVisibility(View.GONE);
        mLlExchangereqBottom.setVisibility(View.VISIBLE);
    }

    // 显示物品详情页
    private void showGoodsDetailPage() {
        mLlGoodsDetailBottom.setVisibility(View.VISIBLE);
        mLlExchangereqBottom.setVisibility(View.GONE);
    }

    /**
     * 从服务器获取物品相关信息
     */
    private void getinitData() {
        Intent intent = getIntent();
        String id = intent.getStringExtra("id");
        ToastUtils.showShort(id);
        // 从数据库中请求数据
        /**
         * .......
         */
    }


    /**
     * 初始化toolbar
     */
    private void initToolbar() {
        toolbar.setNavigationIcon(R.drawable.rc_back_icon);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ToastUtils.showShort("返回");
                finish();
            }
        });
    }


    /**
     * 初始化下拉刷新控件
     */
    private void initSwipeRefresh() {
        mySwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        mySwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        List<CommentEntity> list = getData();
                        refreshData(list);
                        mySwipeRefreshLayout.setRefreshing(false);// true：正在刷新；false：刷新完成
                    }
                }, 2000);
            }
        });
    }

    private void initRecycleView() {
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRecycleView.setLayoutManager(linearLayoutManager);
        List<CommentEntity> mList = getData();
        myCommentAdapter = new CommentRecycleAdapter(context, mList);
        mRecycleView.setAdapter(myCommentAdapter);

        //为RecyclerView添加HeaderView和FooterView
        setHeaderView(mRecycleView);
        setFooterView(mRecycleView);

        // 下拉加载
        mRecycleView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LogUtils.d(TAG, "onScrolled");
                int lastVisibleItemPosition = linearLayoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == myCommentAdapter.getItemCount()) {
                    Log.d("test", "loading executed");

                    boolean isRefreshing = mySwipeRefreshLayout.isRefreshing();
                    if (isRefreshing) {// SwipeRefreshLayout正在刷新
                        myCommentAdapter.notifyItemRemoved(myCommentAdapter.getItemCount());
                        return;
                    }
                    if (!isLoading) {
                        isLoading = true;
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                List<CommentEntity> list = getData();
                                appendData(list);
                                Log.d("test", "load more completed");
                                isLoading = false;
                            }
                        }, 1000);
                    }
                }
            }
        });
    }

    /**
     * 初始化底部导航条
     */
    private void initBottomBar() {
        // 根据数据库中数据设置底部导航栏
        /**
         * .....
         */
        // 已点赞、已收藏等。。
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
           /* case android.R.id.home:
                // Open the navigation drawer when the home icon is selected from the toolbar.
                mDrawerLayout.openDrawer(GravityCompat.START);
                return true;*/
        }
        return super.onOptionsItemSelected(item);
    }


    /**
     * 下拉刷新评论列表
     *
     * @param list
     */
    private void refreshData(List<CommentEntity> list) {
        myCommentAdapter.datas.clear();
        myCommentAdapter.datas.addAll(list);
        myCommentAdapter.notifyDataSetChanged();
        mRecycleView.scrollToPosition(0);
    }

    /**
     * 向评论RecycleView尾部追加数据
     *
     * @param list
     */
    public void appendData(List<CommentEntity> list) {
        myCommentAdapter.datas.addAll(list);
        myCommentAdapter.notifyDataSetChanged();
    }


    private List<CommentEntity> getData() {
        List<CommentEntity> list = new ArrayList<>();
        try {
            JSONArray array = new JSONArray();
            for (int i = 0; i < 3; i++) {
                JSONObject obj = new JSONObject();

                obj.put("headImgUrl", "http://f.hiphotos.baidu.com/image/pic/item/09fa513d269759ee50f1971ab6fb43166c22dfba.jpg");

                obj.put("name", "包美丽Y" + i);
                obj.put("date", "2017-06-1" + i);
                obj.put("content", "书籍便宜专卖啦啦啦送到城南长街李家那天，李太太正在请朋友们茶会");
                array.put(obj);
            }
            list = GsonUtils.jsonToList(array.toString(), CommentEntity.class);
            LogUtils.d(TAG, list.size());
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
        return list;
    }

    private void setHeaderView(RecyclerView view) {
        View header = LayoutInflater.from(this).inflate(R.layout.goodsdetail_list_header, view, false);
        // 初始化recycleview的header中各控件
//        初始化九宫格效果
        NineGridLayout mNineGrideLayout = (NineGridLayout) header.findViewById(R.id.ngl_goodsItem_images);
        mNineGrideLayout.setIsShowAll(false); //当传入的图片数超过9张时，是否全部显示
//        mNineGrideLayout.setSpacing(5); //动态设置图片之间的间隔
        mNineGrideLayout.setUrlList(Arrays.asList(mUrls)); //最后再设置图片url
        myCommentAdapter.setHeaderView(header);
    }

    private void setFooterView(RecyclerView view) {
        View footer = LayoutInflater.from(this).inflate(R.layout.default_loading, view, false);
        myCommentAdapter.setFooterView(footer);
    }

    @Override
    public void setListener() {
        mTvLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                processLike();
            }
        });
        mTvStar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                processStar();
            }
        });
        mTvComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCommentDialog();

            }
        });
        mTvWant.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showExchangeGoodsDialog();
            }
        });

        mTvAgree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!hasAgreed) {
                    processAgree();
                } else {
                    clearRefuseAndAgreeState();
                }
            }
        });
        mTvRefuse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!hasRefused) {
                    processRefuse();
                } else {
                    clearRefuseAndAgreeState();
                }
            }
        });
    }

    private void clearRefuseAndAgreeState() {
        hasAgreed = false;
        hasRefused = false;
        mTvAgree.setText("暂且同意");
        mTvRefuse.setText("残忍拒绝");
    }

    /**
     * 拒绝换物请求
     */
    private void processRefuse() {
        // 向请求者推送消息
        ToastUtils.showShort("拒绝");
        /**
         * ...数据库
         */
        hasRefused = true;
        mTvRefuse.setText("已拒绝");
//        mTvAgree.setEnabled(false);
//        mTvAgree.setBackgroundColor(ContextCompat.getColor(context, android.R.color.darker_gray));
    }

    /**
     * 同意换物请求所做的处理
     */
    private void processAgree() {
        // 向请求者推送消息
        ToastUtils.showShort("同意");
        hasAgreed = true;
        mTvAgree.setText("已同意");
//        mTvRefuse.setEnabled(false);
//        mTvAgree.setBackgroundColor(ContextCompat.getColor(context, android.R.color.darker_gray));
    }

    /**
     * 点赞处理逻辑
     */
    private void processLike() {
        /**
         * .....连接服务器处理
         */
        if (hasLiked) {
            // 取消点赞
            Drawable drawable = getResources().getDrawable(R.drawable.ic_like_border_24dp);
/// 这一步必须要做,否则不会显示.
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            mTvLike.setCompoundDrawables(null, drawable, null, null);
            mTvLike.setText("点赞");
        } else {
            // 点赞
            Drawable drawable = getResources().getDrawable(R.drawable.ic_like_24dp);
/// 这一步必须要做,否则不会显示.
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            mTvLike.setCompoundDrawables(null, drawable, null, null);
            mTvLike.setText("已赞");
        }
        hasLiked = !hasLiked;
    }

    /**
     * 收藏处理逻辑
     */
    private void processStar() {
        /**
         * .....连接服务器处理
         */
        if (hasStared) {
            // 取消收藏
            Drawable drawable = getResources().getDrawable(R.drawable.ic_star_border_24dp);
/// 这一步必须要做,否则不会显示.
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            mTvStar.setCompoundDrawables(null, drawable, null, null);
            mTvStar.setText("收藏");
        } else {
            Drawable drawable = getResources().getDrawable(R.drawable.ic_star_24dp);
/// 这一步必须要做,否则不会显示.
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            mTvStar.setCompoundDrawables(null, drawable, null, null);
            mTvStar.setText("已收藏");
        }
        hasStared = !hasStared;

    }

    /**
     * 将对话框在底部铺满屏幕显示
     *
     * @param dialog
     */
    private void showDialog(AlertDialog dialog) {
        //透明状态栏
        Window window = dialog.getWindow();
        // 设置软键盘弹出方式
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        //此处可以设置dialog显示的位置
        window.setGravity(Gravity.BOTTOM);
//        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //设置背景颜色,只有设置了这个属性,宽度才能全屏MATCH_PARENT
        window.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        // 一定要设置padding，否则不可充满
        window.getDecorView().setPadding(0, 0, 0, 0);

        WindowManager.LayoutParams mWindowAttributes = dialog.getWindow().getAttributes();
        mWindowAttributes.width = ScreenUtils.getScreenWidth((Activity) context);
        mWindowAttributes.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(mWindowAttributes);
        dialog.show();
    }

    /**
     * 显示“评论”对话框
     */
    private void showCommentDialog() {
        LayoutInflater inflater = getLayoutInflater().from(context);
//        ViewGroup root= (ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content);
//        View dialogView = inflater.inflate(R.layout.dialog_comment,root,false);
        View dialogView = inflater.inflate(R.layout.dialog_comment, null);
        AlertDialog dialog = new AlertDialog.Builder(context)
                .setView(dialogView)
                .create();
        showDialog(dialog);
    }

    /**
     * 显示“我想要”对话框
     */
    private void showExchangeGoodsDialog() {
        // 必须
        currentNum = -1;
        if (dialog == null) {
            LayoutInflater inflater = getLayoutInflater().from(context);
            View dialogView = inflater.inflate(R.layout.dialog_want, null);

            ListView mListViewGoods = (ListView) dialogView.findViewById(R.id.lv_wantdialog_list);
            Button mBtnComplete = (Button) dialogView.findViewById(R.id.btn_wantdialog_complete);
            EditText mEtRemark = (EditText) dialogView.findViewById(R.id.tv_wantdialog_remark);
            String remark = mEtRemark.getText().toString();
            setupMyGoodsListview(mListViewGoods);
            setupmBtnComplete(mBtnComplete, remark);

            dialog = new AlertDialog.Builder(context)
                    .setView(dialogView)
                    .create();

        }
        showDialog(dialog);
    }

    /**
     * 设置“我想要”界面中的“完成”按钮
     *
     * @param mBtnComplete
     */
    private void setupmBtnComplete(Button mBtnComplete, final String remark) {
        mBtnComplete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (currentNum == -1) {
                    dialog.dismiss();
                } else {
                    // 若选中了某一物品，则操作数据库
                    SimpleGoodsListEntity selectedGoodsItem = myGoodsListAdapter.getmDatas().get(currentNum);
                    ToastUtils.showShort(selectedGoodsItem.getTitle() + "," + remark);
                    dialog.dismiss();
                }
            }
        });
    }

    /**
     * 设置“我想要”界面中的Listview
     *
     * @param myGoodsList
     */
    private void setupMyGoodsListview(ListView myGoodsList) {
        List<SimpleGoodsListEntity> mDatas = getMyGoodsListData();
        myGoodsListAdapter = new GoodsListAdapter(context, mDatas);
        myGoodsList.setAdapter(myGoodsListAdapter);
        myGoodsList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        myGoodsList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                for (SimpleGoodsListEntity simpleGoodsListEntity : myGoodsListAdapter.getmDatas()) {
                    simpleGoodsListEntity.setHasChecked(false);
                }
                if (currentNum == -1) { //选中
                    myGoodsListAdapter.getmDatas().get(position).setHasChecked(true);
                    currentNum = position;
                } else if (currentNum == position) { //同一个item选中变未选中
                    currentNum = -1;
                } else if (currentNum != position) { //不是同一个item选中当前的，去除上一个选中的
                    myGoodsListAdapter.getmDatas().get(position).setHasChecked(true);
                    currentNum = position;
                }
                ToastUtils.showShort("当前被选中项:" + currentNum + "." + myGoodsListAdapter.getmDatas().get(position).getTitle());
                myGoodsListAdapter.notifyDataSetChanged();//刷新adapter
            }
        });
    }

    private List<SimpleGoodsListEntity> getMyGoodsListData() {
        List<SimpleGoodsListEntity> list = new ArrayList<>();
        try {
            JSONArray array = new JSONArray();
            for (int i = 0; i < 6; i++) {
                JSONObject obj = new JSONObject();
                obj.put("title", "包美丽Y" + i);
                obj.put("time", "2017-06-1" + i);
                array.put(obj);
            }
            list = GsonUtils.jsonToList(array.toString(), SimpleGoodsListEntity.class);
            LogUtils.d(TAG, list.size());
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
        return list;
    }


}
